# -*- encoding=utf8 -*-

import os
import sys
import re
import shutil
import json

import urllib.request
import urllib.parse
import bs4

def ct_getPrivateSpecsFolder():
    '''获取本地私有仓库的目录
    '''
    tmp_folders = ["creatoo", "andney", "gitee-andney-pod-specs", "pod-specs"]
    for item in tmp_folders:
        a = os.path.join(os.path.expanduser('~'), ".cocoapods/repos", item, "Specs")
        if os.path.exists(a):
            return a
    return None
    

def ct_getDirList(path):
    '''获取目录下的所有文件夹名称
    '''
    tmpList = []

    fileList = os.listdir(path)
    for i in range(len(fileList)):
        fileName = fileList[i]
        if os.path.isdir(path + "/" + fileName):
            tmpList.append(fileName)

    return tmpList

def ct_enumeratePodSpecs(path, callback, tag=None):
    '''枚举CocoaPods仓库
    '''
    topFolderList = ct_getDirList(path)

    for top in topFolderList:
        firstFolder = path + "%s/" % top
        middleFolderList = ct_getDirList(firstFolder)

        for middle in middleFolderList:
            secondFolder = firstFolder + "%s/" % middle
            bottomFolderList = ct_getDirList(secondFolder)

            for bottom in bottomFolderList:
                thirdFolder = secondFolder + "%s/" % bottom

                destFolderList = ct_getDirList(thirdFolder)

                for file_name in destFolderList:
                    callback(file_name, thirdFolder + "%s/" % file_name, tag)

def ct_copyFile(srcPath, destPath, removeOld=False):
    '''拷贝文件
    '''
    if os.path.isdir(destPath) == True and os.path.exists(destPath) == False:
        os.makedirs(destPath)

    if os.path.isfile(srcPath):
        target_path = ""
        if os.path.isdir(destPath) or destPath.endswith("/"):
            if destPath.endswith("/"):
                target_path = destPath + ct_getLastComponent(srcPath)
            else:
                target_path = destPath + "/" + ct_getLastComponent(srcPath)
        else:
            target_path = destPath

        if os.path.exists(target_path) == True and removeOld:
            os.remove(target_path)

        print(target_path)
        ct_createFolderIfNeeded(target_path)
        print(target_path)

        shutil.copyfile(srcPath, target_path)

    elif os.path.isdir(srcPath) == True:
        if os.path.exists(destPath) == True and removeOld:
            os.removedirs(destPath)

        shutil.copytree(srcPath, destPath)


def ct_getLastComponent(path):
    '''获取路径中的最后一个文件(夹)名称
    '''
    tmpList = path.split("/")
    for item in reversed(tmpList):
        if len(item) > 0:
            return item
    return ""


def ct_createFolderIfNeeded(path):
    '''创建文件夹
    '''
    if os.path.isdir(path):
        if os.path.exists(path) == False:
            os.makedirs(path)
    else:
        index = path.rfind("/")
        if index >= 0:
            folder = path[0:index+1]
            if os.path.exists(folder) == False:
                os.makedirs(folder)

def ct_writeToFile(path, obj):
    '''写入文件

    Args:
        path: 文件路径
        obj: 要写入的对象（str、list、dict）
    '''
    if isinstance(obj, list) or isinstance(obj, dict):
        content = json.dumps(obj, indent=4, ensure_ascii=False)
    elif isinstance(obj, str):
        content = obj
    else:
        print("invalid content to write.")
        print(type(obj))
        print(obj)
        return False

    with open(path, 'w') as f:
        f.write(content)
        f.close()
        return True

def ct_getFileContent(path):
    '''读取文件
    '''
    with open(path, 'r') as f:
        txtContent = f.read()
        f.close()
        return txtContent

def ct_versionCompare(ver1, ver2, flag="."):
    '''版本号比较
        
    Args:
        flag: 版本号分隔符

    Returns:
        -1: 参数错误
        0: 相等
        1: v1 小于 v2
        2: v1 大于 v2
    '''
    
    if not (isinstance(ver1, str) and isinstance(ver2, str)):
        return -1
    
    v1List = ver1.split(flag)
    v2List = ver2.split(flag)
    for i in range(0, max(len(v1List), len(v2List))):
        v1 = v1List[i] if i<len(v1List) else None
        v2 = v2List[i] if i<len(v2List) else None
        
        if v1 and v2:
            if v1 == v2: continue
            
            if re.match(r"^[0-9\.]+$", v1) and re.match(r"^[0-9\.]+$", v2):
                # 全是数字
                if int(v1) < int(v2):   return 1
                elif int(v1) > int(v2): return 2
            else:
                if v1<v2:   return 1
                elif v1>v2: return 1
            
        elif v1 and not v2: return 2
        elif v2 and not v1: return 1
    
    return 0

def ct_findBiggestVersion(vList):
    '''查找数组中的最大版本号
    '''
    if len(vList) == 0:
        return ""
    
    biggestVersion = vList[0]
    for i in range(1,len(vList)):
        if ct_versionCompare(vList[i], biggestVersion) == 2:
            biggestVersion= vList[i]

    return biggestVersion

def ct_getHtmlContent(url):
    '''模拟浏览器访问url并获取页面内容
    '''
    user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
    headers = { "User-Agent" : user_agent}
    request = urllib.request.Request(url, headers=headers)
    response = urllib.request.urlopen(request)
    return response.read()

def ct_parseHTML(url, encoding="gbk"):
    '''爬取整个网页内容并解析
    '''
    html_doc = ct_getHtmlContent(url)
    return bs4.BeautifulSoup(html_doc, 'html.parser', from_encoding=encoding)